package pers.cz.chat.filter;

import io.netty.channel.Channel;
import pers.cz.chat.constants.Commands;
import pers.cz.jefconfig.config.JefConfiguration;
import pers.cz.netty.config.NettyConfigItem;
import pers.cz.netty.filter.FilterHandler;
import pers.cz.netty.filter.FilterHandlerContext;
import pers.cz.netty.protocal.Message;
import pers.cz.netty.protocal.MsgType;

/**
 * @program: Jef-Chat
 * @description: 群聊
 * @author: Cheng Zhi
 * @create: 2025-01-30 21:02
 **/
public class CreateGroupFilter implements FilterHandler<Message, Channel> {

    @Override
    public boolean approve(Message message, Channel channel, FilterHandlerContext<Message,Channel> handlerContext) {

        Object contentOriginal = message.getContent();
        if (contentOriginal instanceof String) {
            String content = (String) contentOriginal;
            if (content.trim().toLowerCase().startsWith(Commands.CREATEGROUP.getCommand())) {
                // 创建群聊
                message.setIp(JefConfiguration.get(NettyConfigItem.NETTY_SERVER_IP));
                message.setPort(JefConfiguration.getInt(NettyConfigItem.NETTY_SERVER_PORT, 9999));
                message.setMsgType(MsgType.CREATEGROUP);
                String groupName = getGroupName();
                String groupInfo = ScannerImpl.getInput("请指定群组成员（多个成员使用空格隔开）：");
                groupInfo = groupInfo + " " + message.getAttachment("username");
                message.addAttachment("groupName", groupName);
                message.addAttachment("groupInfo", groupInfo);
            }
        }
        return handlerContext.doFilter(message, channel);
    }

    private String getGroupName() {
        String groupName = "";
        while (!groupName.startsWith("group-")) {
            groupName = ScannerImpl.getInput("请输入群组名称(必须以“group-”开头)：");
        }
        return groupName;
    }
}
